<template>
  <div class="pf-flex">
    <div class="pf-w-15 pf-p-10 pf-mr-10 pf-bgwhite">
      <el-button icon="Refresh" size="mini" @click="refreshComp"></el-button>
      <el-button type="primary" size="mini" @click="createComp">添加</el-button>
      <el-tree
        class="pf-mt-10"
        :data="treeData"
        :props="{
          children: 'children',
          label: 'name'
        }"
        node-key="id"
        :current-node-key="activeNode.id"
        @node-click="handleNodeClick"
        :highlight-current="true"
      ></el-tree>
    </div>
    <div class="pf-flex-1 pf-p-10 pf-bgwhite">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane class="pf-mt-10" label="部门配置" name="dept">
          <div class="pf-bgwhite pf-p-10">
            <div class="pf-mt-20 pf-text-left">
              <el-button icon="Refresh" @click="refreshDept"></el-button>
              <el-button type="primary" @click="createDept">新建</el-button>
              <el-button @click="deleteDept">删除</el-button>
            </div>
            <pf-table
              class="pf-mt-20"
              :config="deptConfig"
              :data="deptData"
              :page-param="pageParam"
              @page-size-change="pageSizeChange"
              @page-change="pageChange"
              @current-page-change="pageChange"
            >
              <el-table-column label="操作" fixed="right" width="80">
                <template #default="scope">
                  <el-tooltip effect="light" placement="left" trigger="hover">
                    <component :is="'Menu'" class="el-button--text" style="width: 18px"></component>
                    <template #content>
                      <div class="pf-flex pf-flex-column pf-flex-0">
                        <el-button
                          @click="handleClick(scope.row, 'edit')"
                          link
                          type="primary"
                          size="mini"
                          >编辑</el-button
                        >
                      </div>
                    </template>
                  </el-tooltip>
                </template>
              </el-table-column>
            </pf-table>
          </div>
        </el-tab-pane>
        <el-tab-pane class="pf-mt-10" label="用户配置" name="user">
          <div class="pf-bgwhite pf-p-10">
            <div class="pf-mt-20 pf-text-left">
              <el-button icon="Refresh" @click="refreshUser"></el-button>
              <el-button type="primary" @click="createUser">新建</el-button>
              <el-button @click="deleteUser">删除</el-button>
            </div>
            <pf-table
              class="pf-mt-20"
              :config="userConfig"
              :data="userData"
              :page-param="userPageParam"
              @page-size-change="userPageSizeChange"
              @page-change="userPageChange"
              @current-page-change="userPageChange"
            >
              <el-table-column label="操作" fixed="right" width="80">
                <template #default="scope">
                  <el-tooltip effect="light" placement="left" trigger="hover">
                    <component :is="'Menu'" class="el-button--text" style="width: 18px"></component>
                    <template #content>
                      <div class="pf-flex pf-flex-column pf-flex-0">
                        <el-button
                          @click="handleClick(scope.row, 'edit-user')"
                          link
                          type="primary"
                          size="mini"
                          >编辑</el-button
                        >
                      </div>
                    </template>
                  </el-tooltip>
                </template>
              </el-table-column>
            </pf-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog title="新增公司" v-model="show">
      <pf-form
        ref="compForm"
        @changeEvent="compFormChange"
        :config="compFormConfig"
        :model="compInfo"
      ></pf-form>
      <template #footer>
        <div class="pf-text-right">
          <el-button type="primary" @click="confirmCreateComp">确认</el-button>
          <el-button @click="show = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="新增部门" v-model="show1">
      <pf-form
        ref="deptFormRef"
        @changeEvent="deptFormRefChange"
        :config="deptFormConfig"
        :model="deptInfo"
      >
        <template v-slot:deptManager-slot>
          <i class="el-icon-user" @click="openUserListDialog"
        /></template>
      </pf-form>
      <template #footer>
        <div class="pf-text-right">
          <el-button type="primary" @click="confirmCreateDept">确认</el-button>
          <el-button @click="show1 = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <UserListDialog
      :show="userListDialog"
      @confirm="closeUserListDialog"
      @close="closeUserListDialog"
    ></UserListDialog>
    <user-info-dialog
      :user-info="userInfo"
      :tree-data="treeData"
      :show="show2"
      @close="closeUserInfoDialog"
    ></user-info-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, Ref, watch } from 'vue';
import { TNode, useOrg } from '@/views/system/org/use-org';
import { useTenant } from '@/views/system/tenant/use-tenant';
import { useNotice } from '@/components/element-plus/notice';
import {
  useData,
  emptyForm,
  FormModel,
  emptyTable,
  TableModel,
  Options,
  useAuth
} from 'pf-component';
import { FormNameEnum } from '@/constants/enum/form-name.enum';
import { TableNameEnum } from '@/constants/enum/table-name.enum';
import { useGuest } from '@/views/system/guest/use-guest';

export default defineComponent({
  name: 'User',
  setup() {
    const { companyTreeList, addCompany, addDept, deptList, findNodeById, tNodeToOptions } =
      useOrg();
    const { pageByOrg } = useGuest();
    const pageParam: any = reactive({ total: 0, pageSize: 10, pageNum: 1 });
    const userPageParam: any = reactive({ total: 0, pageSize: 10, pageNum: 1 });
    const pageChange = (val: number) => {
      pageParam.pageNum = val;
      refreshDept();
    };
    const pageSizeChange = (val: number) => {
      pageParam.pageSize = val;
      refreshDept();
    };
    const userPageChange = (val: number) => {
      pageParam.pageNum = val;
      refreshUser();
    };
    const userPageSizeChange = (val: number) => {
      pageParam.pageSize = val;
      refreshUser();
    };
    const activeTab = ref('dept');
    const activeNode: Ref<TNode> = ref({} as any);
    const treeData: Ref<TNode[]> = ref([]);

    const show = ref(false);
    const compForm = ref(null);
    const compFormConfig: Ref<FormModel> = ref(emptyForm);
    const compInfo: Ref<any> = ref({} as any);
    const refreshComp = (): Promise<void> => {
      return companyTreeList().then(res => {
        treeData.value = res;
        activeNode.value = treeData.value.length > -1 ? treeData.value[0] : ({} as any);
      });
    };
    const createComp = () => {
      show.value = true;
    };
    const confirmCreateComp = () => {
      (compForm.value as any).validate((val: boolean) => {
        if (val) {
          addCompany(compInfo.value, treeData).then(res => {
            if (res) {
              show.value = false;
            }
          });
        }
      });
    };
    const show1 = ref(false);
    const deptConfig: Ref<TableModel> = ref(emptyTable);
    const deptData: Ref<any[]> = ref([]);
    const deptFormRef = ref(null);
    const deptFormConfig: Ref<FormModel> = ref(emptyForm);
    const deptInfo: Ref<any> = ref(null as any);
    const refreshDept = () => {
      deptList(pageParam, activeNode.value.id, activeNode.value.isCom).then(res => {
        deptData.value = res;
      });
    };
    const createDept = () => {
      // TODO wangjie 部门弹框的管理员数据需要指定当前选中公司下的用户
      show1.value = true;
    };
    const deleteDept = () => {
      useNotice().message.error('待完善');
    };
    const confirmCreateDept = () => {
      (deptFormRef.value as any).validate((val: boolean) => {
        if (val) {
          addDept(deptInfo.value, treeData).then(res => {
            if (res) {
              show1.value = false;
            }
          });
        }
      });
    };
    const show2 = ref(false);
    const userConfig: Ref<TableModel> = ref(emptyTable);
    const userData: Ref<any[]> = ref([]);
    const userInfo: Ref<any> = ref({} as any);
    const createUser = () => {
      show2.value = true;
      userInfo.value = {};
    };
    const deleteUser = () => {
      useNotice().message.error('待完善');
    };
    const closeUserInfoDialog = (ok?: boolean) => {
      show2.value = false;
      if (ok) {
        refreshUser();
      }
    };
    const refreshUser = () => {
      pageByOrg({ ...userPageParam, id: activeNode.value.id, isCom: activeNode.value.isCom }).then(
        res => {
          userData.value = res.records;
          userPageParam.total = res.total;
        }
      );
    };
    const userListDialog: Ref<boolean> = ref(false);
    const openUserListDialog = () => {
      userListDialog.value = true;
    };
    const closeUserListDialog = (res: any) => {
      userListDialog.value = false;
      if (res && res.length === 1) {
        const obj = res[0];
        deptInfo.value.deptManager = obj.userId;
      }
    };
    watch(activeNode, () => {
      refreshDept();
      refreshUser();
    });
    const handleNodeClick = (data: TNode) => {
      activeNode.value = data;
    };
    const handleTabClick = (data: any) => {
      console.log(data);
    };
    const handleClick = (data: any, cmd: string) => {
      switch (cmd) {
        case 'edit':
          useNotice().message.error(cmd + '待完善');
          break;
        case 'edit-user':
          userInfo.value = data;
          show2.value = true;
          break;
        default:
          useNotice().message.error(cmd + '未找到');
          break;
      }
    };

    const deptFormRefChange = (newV: any, prop: string) => {
      if (prop === 'deptComId') {
        const node = findNodeById(treeData.value, newV);
        if (node) {
          deptFormConfig.value?.setOptions(
            'deptSupDeptId',
            tNodeToOptions(node.children.filter(t => !t.isCom))
          );
        } else {
          deptFormConfig.value?.setOptions('deptSupDeptId', []);
        }
      }
    };
    const compFormChange = (newV: any, prop: string) => {};
    onMounted(() => {
      Promise.all([
        useData().loadForm([
          {
            name: FormNameEnum.companyForm,
            config: compFormConfig,
            info: compInfo
          },
          { name: FormNameEnum.deptForm, config: deptFormConfig, info: deptInfo }
        ]),
        useData().loadTable([
          { name: TableNameEnum.sysDept, config: deptConfig },
          { name: TableNameEnum.sysUser, config: userConfig }
        ])
      ]).then(ress => {
        if (ress.findIndex(res => !res) === -1) {
          const fieldIdx = deptFormConfig.value.fields?.findIndex(v => v.prop === 'deptManager');
          if (fieldIdx !== -1) {
            deptFormConfig.value.fields[fieldIdx].append = 'deptManager-slot';
          }
          refreshComp().then(() => {
            const tenId = useAuth().getUserInfo().tenId;
            deptFormConfig.value?.setOptions(
              'deptComId',
              tNodeToOptions(
                treeData.value.filter(t => t.isCom && t.supId === tenId),
                true
              )
            );
            compFormConfig.value?.setOptions(
              'comSupComId',
              tNodeToOptions(
                treeData.value.filter(t => t.isCom && t.supId === tenId),
                true
              )
            );
          });
        }
      });
    });

    return {
      activeTab,
      activeNode,
      treeData,
      show,
      compFormConfig,
      compForm,
      compInfo,
      refreshComp,
      createComp,
      confirmCreateComp,
      show1,
      deptFormConfig,
      deptFormRef,
      deptInfo,
      deptConfig,
      deptData,
      refreshDept,
      createDept,
      confirmCreateDept,
      deleteDept,
      show2,
      userConfig,
      userData,
      userInfo,
      closeUserInfoDialog,
      refreshUser,
      createUser,
      deleteUser,
      handleNodeClick,
      handleTabClick,
      handleClick,
      deptFormRefChange,
      compFormChange,
      userListDialog,
      openUserListDialog,
      closeUserListDialog,
      userPageParam,
      pageParam,
      pageChange,
      userPageChange,
      pageSizeChange,
      userPageSizeChange
    };
  }
});
</script>

<style scoped lang="scss"></style>
